package com.gyms.fragment;

import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.classic.okhttp.AppChangeUtils;
import com.classic.okhttp.Cons;
import com.classic.okhttp.beans.HVShareActivityBean;
import com.classic.okhttp.beans.HVUserBaseInfoBean;
import com.classic.okhttp.beans.HVUserOtherInfoBean;
import com.classic.okhttp.services.IUserService;
import com.classic.okhttp.zmoumall.http.ObjectCallback;
import com.gyms.R;
import com.gyms.activity.CollectionActivity;
import com.gyms.activity.MyCouponActivityNew;
import com.gyms.activity.MyInformationActivity;
import com.gyms.activity.MyMessageActivity;
import com.gyms.activity.MyOrderActivity;
import com.gyms.activity.QRCodeActivity;
import com.gyms.activity.ReportActivity;
import com.gyms.base.BaseActivity;
import com.gyms.base.BaseFragment;
import com.gyms.constant.Constants;
import com.gyms.manager.CommonDialogUtils;
import com.gyms.manager.DataCenter;
import com.gyms.manager.StateUtils;
import com.gyms.view.bottomview.ShareDialog;
import com.orhanobut.logger.Logger;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import butterknife.BindView;
import butterknife.OnClick;
import constant.EventConstant;
import glide.ImageLoaderUtils;
import utils.DataUtil;
import utils.StringUtils;
import weight.ComDialog;
import weight.UiEvent;

import static com.gyms.R.id.llayout_exit;
import static com.gyms.R.id.llayout_yaoqing;

/**
 * 我的fragment
 */
public class MineFragment extends BaseFragment {
    @BindView(R.id.llayout_report)
    LinearLayout llayoutReport;
    @BindView(R.id.llayout_cards)
    LinearLayout llayoutCards;
    @BindView(R.id.llayout_collection)
    LinearLayout llayoutCollection;
    @BindView(R.id.llayout_message)
    LinearLayout llayoutMessage;
    @BindView(llayout_yaoqing)
    LinearLayout llayoutYaoqing;
    @BindView(R.id.llayout_tomyinformation)
    LinearLayout llayoutTomyinformation;
    @BindView(R.id.llayout_qrcode)
    LinearLayout llayoutQrcode;
    @BindView(R.id.llayout_about)
    LinearLayout llayoutAbout;
    @BindView(R.id.tv_login_tip)
    TextView tvLoginTip;

    DataCenter mDataCenter;
    @BindView(R.id.profile_image)
    ImageView profileImage;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.tv_phone)
    TextView tvPhone;
    @BindView(R.id.ll_my_order)
    LinearLayout llMyOrder;
    @BindView(llayout_exit)
    LinearLayout llayoutExit;
    @BindView(R.id.tv_messagenum)
    TextView tvMessagenum;
    @BindView(R.id.tv_cardsnum)
    TextView tvCardsnum;
    @BindView(R.id.tv_collectsnum)
    TextView tvCollectsnum;
    @BindView(R.id.iv_message_red)
    ImageView ivMessageRed;//红点
    @BindView(R.id.tv_app_id)
    TextView tvAppId;
    @BindView(R.id.tv_pay_remind)
    TextView mTvRemind;
    @BindView(R.id.line_invite)
    View mLineInvite;//邀请好友下面的下划线
    @BindView(R.id.temp_view)
    View mTempView;//邀请好友下面的下划线
    @BindView(R.id.fl_phone_and_str)
    FrameLayout nFlPhoneAndStr;//邀请好友下面的下划线

    @BindView(R.id.tv_change_net)
    LinearLayout mLlChangeNet;//切换服务器
    //联系我们
    @BindView(R.id.ll_contact_us)
    LinearLayout mLlContactUs;

    private long mLeaveTime;//剩余支付时间
    private boolean isRemain;//是否正在提醒
    private boolean isOverTime;//是否超时

    private ShareDialog mShareDialog;

    //分享活动相关

    public Handler mHandlder = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (mLeaveTime > 0) {
                mLeaveTime -= 1;
            }
            StringUtils.updateTextView(mLeaveTime, mTvRemind);
            isOverTime = mTvRemind.getText().toString().equals(getResources().getString(R.string.str_over_time));
            if(isOverTime){
                mTvRemind.setText("");
                mHandlder.removeCallbacksAndMessages(null); //防止当前Activity结束以后,   handler依然继续循环浪费资源
                return;
            }
            mHandlder.sendEmptyMessageDelayed(0,1000);
        }
    };

    @Override
    protected int getLayoutResId() {
        return R.layout.mine_tab;
    }

    @Override
    protected void initView() {
//        createLoadingView("信息加载中",true);
        mLlChangeNet.setVisibility(Cons.isRelease?View.GONE:View.VISIBLE);//更改服务器
        tvAppId.setText("版本号:" + getVersionName());
        //如果是场馆通APP就隐藏邀请好友
        doChangeApp();
        setChangeWorkNet();
    }

    /**
     * 切换服务器
     */

    private void setChangeWorkNet() {
        for(int pos=0;pos<mLlChangeNet.getChildCount();pos++){
            final int mTempPos=pos;
            View view=mLlChangeNet.getChildAt(pos);
            view.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    switch (mTempPos){
                        case 0://内网测试服务
                            Cons.GATEWAY_URL="http://s5.hulanet.cc:8080/hlcg/";
                            break;

                        case 1:// 外网测试服务
                            Cons.GATEWAY_URL="https://c.service.hulasports.com/hlcg/";
                            break;


                        case 2://正式服务
                            Cons.GATEWAY_URL="https://hlcg.hulacgt.com/hlcg/";
                            break;
                    }
                    getActivity().finish();

                }
            });
        }
    }

    /**
     * 更换APP 隐藏邀请好友
     */

    private void doChangeApp() {
        if(AppChangeUtils.isGymApp){
            llayoutYaoqing.setVisibility(View.VISIBLE);
            mLineInvite.setVisibility(View.VISIBLE);
            mTempView.setVisibility(View.GONE);
        }else{
            llayoutYaoqing.setVisibility(View.GONE);
            mLineInvite.setVisibility(View.GONE);
            mTempView.setVisibility(View.INVISIBLE);
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        getUserOtherInfo();
        checkSetView();
    }

    private void checkSetView() {
        //判断是否登录状态
        if (!mDataCenter.checkIsLogin()) {
            tvName.setVisibility(View.GONE);
            tvLoginTip.setVisibility(View.VISIBLE);
            profileImage.setImageResource(R.mipmap.icon_picbig);
            tvPhone.setVisibility(View.GONE);
            llayoutExit.setVisibility(View.INVISIBLE);
            nFlPhoneAndStr.setVisibility(View.VISIBLE);
        } else {
            tvLoginTip.setVisibility(View.GONE);
            tvPhone.setVisibility(View.GONE);
            llayoutExit.setVisibility(View.VISIBLE);
            tvName.setVisibility(View.VISIBLE);
            nFlPhoneAndStr.setVisibility(View.GONE);
        }
    }

    @Override
    protected void initListener() {
        //注册EventBus
        EventBus.getDefault().register(this);
        mDataCenter = DataCenter.getInstance();
        requestInformation();
    }

    @Override
    protected void processLogic() {

    }

    @OnClick({R.id.llayout_cards, R.id.llayout_collection, R.id.llayout_message, R.id.llayout_report, llayout_yaoqing, R.id.llayout_tomyinformation, llayout_exit, R.id.ll_my_order, R.id.llayout_qrcode, R.id.llayout_about,R.id.tv_change_net,R.id.ll_contact_us})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.llayout_message:
                startActivityIsLogin(MyMessageActivity.class, true);
                break;
            case R.id.llayout_cards:
                startActivityIsLogin(MyCouponActivityNew.class, true);
                break;
            case R.id.llayout_collection://收藏
                startActivityIsLogin(CollectionActivity.class, true);
                break;
            case R.id.llayout_qrcode:
                startActivityIsLogin(QRCodeActivity.class, true);
                break;
            case R.id.llayout_report:
                Bundle mBundle=new Bundle();
                mBundle.putString(Constants.LABLE, Constants.FEEDBACK_TEXT);
                startActivityIsLogin(ReportActivity.class,false,mBundle);
                break;
            case llayout_yaoqing://邀请好友
                HVShareActivityBean mHVShareActivityBean=mDataCenter.getHVShareActivityBean();

                if(StateUtils.isShareActivity(mHVShareActivityBean)){//是否是分享活动
                    doActivityShare(mHVShareActivityBean);
                }else {
                    doShowShareDialog();
                }
                break;
            case R.id.llayout_tomyinformation:
                startActivityIsLogin(MyInformationActivity.class, true);
                break;
            case R.id.llayout_about:
                StateUtils.goWebView((BaseActivity) getActivity(),(String) llayoutAbout.getTag(),Cons.aboutUs);
                break;
            case llayout_exit:
                final ComDialog dialog = CommonDialogUtils.dialog(getActivity(),getFragmentManager(),"退出","是否退出登录");
                dialog.setSubmit(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dialog.dismiss();
                        loginOut();
                    }
                });
                dialog.setCancel(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dialog.dismiss();
                    }
                });
                break;
            case R.id.ll_my_order:
                startActivityIsLogin(MyOrderActivity.class, true);
                break;
            case R.id.tv_change_net://切换网络

                break;

            case R.id.ll_contact_us:
                StateUtils.goWebView((BaseActivity) getActivity(),"联系我们",Cons.mContactUs);

                break;

        }
    }

    /**
     * 分享活动
     * @param mHVShareActivityBean mHVShareActivityBean
     */

    private void doActivityShare(HVShareActivityBean mHVShareActivityBean) {
        StateUtils.goWebView((BaseActivity) getActivity(),null,mHVShareActivityBean.getUrl());
    }

    /**
     * 展示分享框
     */

    private void doShowShareDialog() {
        if(null==mShareDialog){
            mShareDialog = new ShareDialog(getActivity(), R.style.BottomToTopAnim);
            mShareDialog.setTitle(Cons.SHARE_TITLE);
            mShareDialog.setTagUrl(Cons.URL_DOWNLOAD);
            mShareDialog.setShareContent(Cons.SHARE_CONTENT);
        }
        mShareDialog.show();
    }

    /**
     * 退出的处理操作
     */

    private void doLoginOut() {
        DataCenter.getInstance().setToken("");
        DataCenter.getInstance().setUser(null);
        //清除本地
        DataUtil.setSharePre(mContext, "token", "");
        initOtherViewData(null);
        checkSetView();
        //退出时倒计时的逻辑
        mHandlder.removeCallbacksAndMessages(null); //防止当前Activity结束以后,   handler依然继续循环浪费资源
        isRemain = false;
        mTvRemind.setText("");
    }

    /**
     * 退出
     */

    private void loginOut() {
        IUserService.quit(getActivity(), false, new ObjectCallback<Object>() {
            @Override
            public void onSuccess(Object response, String message) {
                doLoginOut();
            }

            @Override
            public void onErrorT(int code, Object response, String errorMessage) {
                doLoginOut();
            }

            @Override
            public void onHttpErrorCall(int statusCode) {
                doLoginOut();
            }
        });

    }

    /**
     * 请求个人信息
     */
    private void requestInformation() {
        if (loadingView != null)
            loadingView.show();
        IUserService.getUserBaseInfo(getActivity(), false, new ObjectCallback<HVUserBaseInfoBean>() {
            @Override
            public void onSuccess(HVUserBaseInfoBean response, String message) {
                dialogDis();
                mDataCenter.setUser(response);
                initViewData();
                EventBus.getDefault().post(new UiEvent(EventConstant.S_CODE, response));
            }

            @Override
            public void onErrorT(int code, HVUserBaseInfoBean response, String errorMessage) {
                dialogDis();
                EventBus.getDefault().post(new UiEvent(EventConstant.S_CODE, null));
            }

            @Override
            public void onHttpErrorCall(int statusCode) {
                dialogDis();
                EventBus.getDefault().post(new UiEvent(EventConstant.S_CODE, null));
            }
        });
    }

    /**
     * 获取其它信息
     */
    private void getUserOtherInfo() {
        IUserService.getUserOtherInfo(getActivity(), false, new ObjectCallback<HVUserOtherInfoBean>() {
            @Override
            public void onSuccess(HVUserOtherInfoBean response, String message) {
                initOtherViewData(response);
            }

            @Override
            public void onErrorT(int code, HVUserOtherInfoBean response, String errorMessage) {

            }

            @Override
            public void onHttpErrorCall(int statusCode) {

            }
        });
    }

    /**
     * 填充页面数据
     */
    private void initViewData() {
        if (!StringUtils.isNull(mDataCenter.getUser())) {
            ImageLoaderUtils.displayCircleUrl(mContext, profileImage, mDataCenter.getUser().getImageUrl());
            if (mDataCenter.getUser().getUserName() != null) {
                tvName.setText("" + mDataCenter.getUser().getUserName());
            }
//            tvPhone.setText(phone.replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2"));
            tvPhone.setText(StringUtils.CS(mDataCenter.getUser().getPhone()));
        } else {
            //如果获取用户信息为空就重置
            DataCenter.getInstance().setToken("");
            initOtherViewData(null);
            checkSetView();
        }
    }

    private void initOtherViewData(HVUserOtherInfoBean response) {
        if (!StringUtils.isNull(response)) {
            String text1 = response.getUnreadMessageNum() > 0 ? " " + response.getUnreadMessageNum() : " 0";
            String text2 = response.getUnusedCardNum() > 0 ? " " + response.getUnusedCardNum() : " 0";
            String text3 = response.getCollectionNum() > 0 ? " " + response.getCollectionNum() : " 0";
            setText(text1, text2, text3);
            if (response.getUnreadMessageNum() > 0) {
                ivMessageRed.setVisibility(View.VISIBLE);
            } else {
                ivMessageRed.setVisibility(View.GONE);
            }
            mLeaveTime=response.getOrderPayCountdown();
            Logger.e("mLeaveTime="+mLeaveTime);
            if (mLeaveTime == 0) {//倒计时
                isRemain = false;
            } else {
                if (!isRemain) {
                    mHandlder.sendEmptyMessageAtTime(0, 1000);
                    isRemain = true;
                }
            }

            //
        } else {
            setText("", "", "");
            ivMessageRed.setVisibility(View.GONE);
        }
    }

    private void setText(String text1, String text2, String text3) {
        String mMyMessage="我的消息" + text1;
        String mMyCard ="我的卡券"+text2;
        String mMyCollect="我的收藏" + text3;
        tvMessagenum.setText(StringUtils.setDifTextColor(mMyMessage,4,mMyMessage.length(),getResources().getColor(R.color.c_039df6)));
        tvCardsnum.setText(StringUtils.setDifTextColor(mMyCard,4,mMyCard.length(),getResources().getColor(R.color.c_039df6)));
        tvCollectsnum.setText(StringUtils.setDifTextColor(mMyCollect,4,mMyCollect.length(),getResources().getColor(R.color.c_039df6)));
    }

    /**
     * EventBus 接收事件
     * 刷新我的信息
     *
     * @param uiEvent
     */
    @Subscribe
    public void toReflashMyInfo(UiEvent uiEvent) {
        if (uiEvent.getKey().equals(EventConstant.S_MYINFO)) {
            requestInformation();
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);//销毁的时候注销EventBus
        mHandlder.removeCallbacksAndMessages(null); //防止当前Activity结束以后,   handler依然继续循环浪费资源
    }

    /**
     * 获得版本号
     *
     * @return
     */
    public String getVersionName() {
        String versionName = "";
        int versioncode = 0;
        try {
            // ---get the package info---
            PackageManager pm = mContext.getPackageManager();
            PackageInfo pi = pm.getPackageInfo(mContext.getPackageName(), 0);
            versionName = pi.versionName;
            versioncode = pi.versionCode;
            if (versionName == null || versionName.length() <= 0) {
                return "";
            }
        } catch (Exception e) {
        }
        return versionName;
    }
}
